import 'dart:async';

import 'package:star_author/config/base_configuration.dart';
import 'package:star_author/event_bus/global_event_bus.dart';
import 'package:star_author/event_bus/user_login_event.dart';
import 'package:star_author/utils/common_util/log_util.dart';
import 'package:star_author/utils/http/api_manager.dart';
import 'package:star_author/utils/rong_im/rong_im.dart';

import 'package:star_author/utils/user_util.dart';
import 'package:star_author/utils/utils.dart';
import 'package:star_author/utils/websocket_manage/websocket_manage.dart';
import 'package:star_author/views/login/phone_login.dart';
import 'package:star_author/widgets/alert.dart';
import 'package:star_author/widgets/cover_widget.dart';
import 'package:star_author/widgets/empty_view/v_empty_view.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';

import '../../provider/user.dart';
import '../../utils/common_util/num_util.dart';
import '../../utils/http/http_util.dart';

class UserInfoPage extends StatefulWidget {
  const UserInfoPage({Key? key}) : super(key: key);

  @override
  State<UserInfoPage> createState() => _UserInfoPageState();
}

class _UserInfoPageState extends State<UserInfoPage> {
  Map detail = {};

  late StreamSubscription loginStatusSubscription;

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    loginStatusSubscription.cancel();
  }

  @override
  void initState() {
    super.initState();
    loginStatusSubscription =
        GlobalEventBus().bus.on<UserLoginEvent>().listen((event) {
      if (event.isLogin) {
        LogUtil.v("登录成功--index");
        HttpUtil.commonRequest(
          Get.context!,
          ApiManager.current_tiny,
          isLoading: false,
          isErrorToast: false,
          queryParameters: {
            "scene": "happ-${Get.currentRoute}",
          },
        ).then((value) {
          Provider.of<UserProvider>(context, listen: false)
              .set(key: 'userInfo', value: value.data);
          init();
        });
        setState(() {});
      }
    });

    WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
      init();
    });
  }

  init() {
    Map userInfo = UserUtil.getUserInfo(context) ?? {};

    int? anchorId;
    if (userInfo['anchor'] != null) {
      anchorId = userInfo['anchor']['id'];
    }

    if (anchorId != null) {
      getDetailMap(anchorId);
    }
  }

  void getDetailMap(int id) {
    HttpUtil.commonRequest(
      Get.context!,
      '/api/v1/anchors/$id/statistics',
      isLoading: true,
      isErrorToast: true,
    ).then((value) {
      detail = value.data;
      if (mounted) setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    bool is_login = UserUtil.isLogin(context);
    UserProvider provider = Provider.of<UserProvider>(context, listen: false);
    int id = 0;
    String cover = "";
    String name = "首页";
    bool isAnchor = false;
    if (provider.user!['id'] != 0) {
      //登录
      List maintain_studios = provider.user!['maintain_studios'] ?? [];
      if (maintain_studios.length > 0) {
        id = maintain_studios[0]['id'] ?? 0;
        cover = maintain_studios[0]['vertical_cover'] ?? "";
        name = maintain_studios[0]['name'] ?? "";
        isAnchor = true;
      }
    }
    //主播信息
    Map? anchor = provider.user?['anchor'] ?? {};
    bool isAnchorAccount = false;
    if (anchor?.isNotEmpty ?? false) {
      isAnchorAccount = true;
    }
    LogUtil.v(isAnchorAccount);
    return Scaffold(
      backgroundColor: rgba(245, 245, 245, 1),
      body: SafeArea(
        child: isAnchorAccount
            ? Container(
                child: buildContentWidget(),
                margin: EdgeInsets.only(
                  top: 30.w,
                ),
              )
            : Container(),
      ),
      bottomNavigationBar: Container(
        padding: EdgeInsets.symmetric(
          horizontal: 12.w,
          vertical: 10.w,
        ),
        child: buildBottomBar(),
      ),
    );
  }

  buildContentWidget() {
    return Container(
      width: Get.width,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(4.w),
      ),
      padding: EdgeInsets.only(
        left: 12.w,
        top: 13.w,
        right: 12.w,
        bottom: 20.w,
      ),
      margin: EdgeInsets.symmetric(
        horizontal: 12.w,
      ),
      child: Container(
        width: Get.width - 24.w,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              width: Get.width - 24.w - 20.w,
              child: Stack(
                clipBehavior: Clip.none,
                children: [
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Row(
                        children: [
                          SizedBox(
                            width: 12.w + 54.w,
                          ),
                          Text(
                            "${detail['nickname'] ?? ''}",
                            style: TextStyle(
                              fontSize: 16.sp,
                              color: rgba(51, 51, 51, 1),
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ],
                      ),
                      Container(
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Container(
                              child: Text(
                                "好评率",
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 10.sp,
                                ),
                              ),
                              decoration: BoxDecoration(
                                color: rgba(68, 169, 73, 1),
                                borderRadius: BorderRadius.only(
                                  topLeft: Radius.circular(3.w),
                                  bottomLeft: Radius.circular(3.w),
                                ),
                              ),
                              width: 42.w,
                              height: 20.w,
                              alignment: Alignment.center,
                            ),
                            Container(
                              child: Text(
                                "${NumUtil.multiply(detail['good_rate'] ?? 1.0, 100).toInt()}%",
                                style: TextStyle(
                                  color: rgba(68, 169, 73, 1),
                                  fontSize: 14.sp,
                                ),
                              ),
                              decoration: BoxDecoration(
                                color: rgba(68, 169, 73, 0.08),
                                borderRadius: BorderRadius.only(
                                  topRight: Radius.circular(3.w),
                                  bottomRight: Radius.circular(3.w),
                                ),
                              ),
                              width: 42.w,
                              height: 20.w,
                              alignment: Alignment.center,
                            ),
                            SizedBox(
                              width: 8.w,
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                  Positioned(
                    child: buildCircleCover(
                      cover: "${detail['avatar'] ?? ''}",
                      size: 54,
                    ),
                    top: -22.w,
                  ),
                ],
              ),
            ),
            Container(
              margin: EdgeInsets.only(
                top: 30.w,
                right: 8.w,
                bottom: 12.w,
              ),
              height: 0.5.w,
              color: rgba(238, 238, 238, 1),
            ),
            Text(
              "本场直播数据总览",
              style: TextStyle(
                color: rgba(51, 51, 51, 1),
                fontSize: 14.sp,
                fontWeight: FontWeight.w500,
              ),
            ),
            SizedBox(
              height: 12.w,
            ),
            Wrap(
              runSpacing: 20.w,
              spacing: 0.w,
              children: [
                buildItem('${detail['duration'] ?? 0}h', '直播时长'),
                buildItem('${detail['views_number'] ?? 0}', '观看人数'),
                buildItem('${detail['explain_numer'] ?? 0}', '讲解货品数'),
                buildItem('${detail['good_count'] ?? 0}', '好评数'),
                buildItem('${detail['middle_count'] ?? 5.0}', '中评数'),
                buildItem('${detail['bad_count'] ?? 5.0}', '差评数'),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget buildItem(String data, String text) {
    double item_width = (Get.width - 24.w - 24.w) / 3;
    return Container(
      width: item_width,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            text,
            style: TextStyle(
              color: rgba(153, 153, 153, 1),
              fontSize: 10.sp,
            ),
          ),
          VEmptyView(8.w),
          Text(
            data,
            style: TextStyle(
              color: rgba(51, 51, 51, 1),
              fontWeight: FontWeight.bold,
              fontSize: 18.sp,
            ),
          ),
        ],
      ),
    );
  }

  Widget buildBottomBar() {
    if (!UserUtil.isLogin(context)) {
      return GestureDetector(
        child: Container(
          height: 54.w,
          width: Get.width,
          margin: EdgeInsets.only(
            left: 12.w,
            right: 12.w,
            bottom: 40.w,
          ),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(6.w),
          ),
          child: Center(
            child: Text(
              "登录",
              style: TextStyle(
                fontSize: 16.sp,
                color: rgba(68, 169, 73, 1),
              ),
            ),
          ),
        ),
        onTap: () {
          Get.to(PhoneLoginPage());
        },
      );
    } else {
      return GestureDetector(
        child: Container(
          height: 54.w,
          width: Get.width,
          margin: EdgeInsets.only(
            left: 12.w,
            right: 12.w,
            bottom: 40.w,
          ),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(6.w),
          ),
          child: Center(
            child: Text(
              "退出登录",
              style: TextStyle(
                fontSize: 16.sp,
                color: Colors.red,
              ),
            ),
          ),
        ),
        onTap: () {
          onLoggedOut();
        },
      );
    }
  }

  ///退出登陆
  void onLoggedOut() {
    Alert.showCustomDialog(
        Container(
          child: Text(
            '确定要退出登录吗？',
            textAlign: TextAlign.center,
            style: TextStyle(
              fontWeight: FontWeight.normal,
              decoration: TextDecoration.none,
              fontSize: 16.sp,
              color: ColorConf.normal,
            ),
          ),
        ),
        context,
        confirmText: '确认登出', onConfirm: () async {
      final user = Provider.of<UserProvider>(context, listen: false);
      user.clearToken();
      RongUtil.disconnect();
      setState(() {});

      ///断开ws
      LogUtil.v('WebSocketManage WebSocket连接关闭 - setting');
      WebSocketManage().closeSocket();
    });
  }
}
